<template>
  <div id="questionsSubmitView">
    <a-form :model="searchParams" layout="inline">
      <a-form-item field="questionId" label="题号" style="min-width: 250px">
        <a-input v-model="searchParams.questionId" placeholder="题目id" />
      </a-form-item>
      <a-form-item :model="form" layout="inline">
        <a-form-item field="language" label="编程语言" style="min-width: 200px">
          <a-select
            v-model="searchParams.language"
            :style="{ width: '200px' }"
            placeholder="选择语言"
          >
            <a-option>java</a-option>
            <a-option>cpp</a-option>
            <a-option>go</a-option>
          </a-select>
        </a-form-item>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" @click="doSubmit">搜索</a-button>
      </a-form-item>
    </a-form>
    <a-divider size="0" />
    <a-table
      :column-resizable="true"
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
        showTotal: true,
        showJumper: true,
        showPageSize: true,
      }"
      @page-change="onPageChange"
      @pageSizeChange="onPageSizeChange"
    >
      <template #result="{ record }">
        <!-- 执行状态：等待中、判题中 -->
        <template v-if="record.status == 0 || record.status == 1">
          <a-tag size="large" loading>Loading</a-tag>
        </template>
        <template
          v-else-if="
            record.judgeInfo.message !== undefined &&
            record.judgeInfo.message !== null &&
            record.judgeInfo.message !== '' &&
            judgeResultObjtList[record.judgeInfo.message] !== undefined &&
            judgeResultObjtList[record.judgeInfo.message] !== null
          "
        >
          <a-tag
            size="large"
            :color="getJudgeResultStyleColor(record.judgeInfo.message)"
          >
            {{ judgeResultObjtList[record.judgeInfo.message].text }}
          </a-tag>
        </template>
        <template
          v-else-if="
            record.judgeInfo.message !== undefined &&
            record.judgeInfo.message !== null &&
            record.judgeInfo.message !== ''
          "
        >
          <a-tag size="large" :color="getJudgeResultStyleColor('default')">
            {{ record.judgeInfo.message }}
          </a-tag>
        </template>
        <template v-else>
          <span>{{ record.judgeInfo.message }}</span>
        </template>
      </template>
      <template #memory="{ record }">
        <!--        <template v-if="record.judgeInfo.memory <= 1024">-->
        <!--          <span>{{ record.judgeInfo.memory }} byte</span>-->
        <!--        </template>-->
        <!--        <template v-else-if="record.judgeInfo.memory <= 1024 * 1024">-->
        <!--          <span>{{ (record.judgeInfo.memory / 1024).toFixed(2) }} KB</span>-->
        <!--        </template>-->
        <span>{{ (record.judgeInfo.memory / 1).toFixed(2) }} MB</span>
      </template>
      <template #time="{ record }">
        <template v-if="record.judgeInfo.time < 1000">
          <span>{{ record.judgeInfo.time }} ms</span>
        </template>
        <template v-else>
          <span>{{ (record.judgeInfo.time / 1000).toFixed(2) }} S</span>
        </template>
      </template>
      <!--      判题状态-->
      <template #status="{ record }">
        <template v-if="record.status === 0">
          <a-tag color="#168cff">待判题</a-tag>
        </template>
        <template v-else-if="record.status === 1">
          <a-tag color="#ffb400">判题中</a-tag>
        </template>
        <template v-else-if="record.status === 2">
          <a-tag color="green">判题成功</a-tag>
        </template>
        <template v-else-if="record.status === 3">
          <a-tag color="red">判题失败</a-tag>
        </template>
      </template>
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD:HH:mm:ss") }}
      </template>
      <template #optional="{ record }">
        <template
          v-if="
            store.state.user.loginUser.id == record.userId ||
            store.state.user.loginUser.userRole == AccessEnum.ADMIN
          "
        >
          <a-button
            type="secondary"
            shape="round"
            @click="toViewQuestionSubmitViewPage(record)"
          >
            查看详情
          </a-button>
        </template>
        <!--        <template v-else></template>-->
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch, watchEffect } from "vue";
import {
  Question,
  QuestionQueryRequest,
  QuestionSubmitControllerService,
  QuestionSubmitVO,
  QuestionSumitQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment";
import { useStore } from "vuex";
import AccessEnum from "@/access/accessEnum";

// const show = ref(true);
const dataList = ref([]);
const total = ref(0);
//搜索条件
const searchParams = ref<QuestionSumitQueryRequest>({
  questionId: undefined,
  language: undefined,
  pageSize: 10,
  current: 1,
});

const loadData = async () => {
  if (searchParams.value.questionId) {
    searchParams.value.questionId = Number(searchParams.value.questionId);
  } else {
    searchParams.value.questionId = undefined;
  }
  const res =
    await QuestionSubmitControllerService.listQuestionSubmitByPageUsingPost(
      searchParams.value
    );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败" + res.message);
  }
};

const refreshFlag = ref(false); // 哨兵变量
const tableRef = ref();

// 设置定时器，每隔一段时间执行一次 loadData 函数
const intervalId = setInterval(() => {
  if (refreshFlag.value) {
    console.log("定时任务");
    loadData();
    refreshFlag.value = false; // 重置哨兵变量
  }
}, 5000); // 每隔（3 秒）执行一次

//监听loadData()函数中的变量searchParams里值的是否改变，改变了会触发页面重新加载
watchEffect(() => {
  if (!refreshFlag.value) {
    refreshFlag.value = true; // 设置哨兵变量，触发定时任务
  }
  loadData();
});

// 在组件销毁时清除定时器
onBeforeUnmount(() => {
  clearInterval(intervalId);
});
/**
 * 页面加载时，请求后端数据
 */
onMounted(() => {
  loadData();
});

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const columns = [
  {
    title: "提交号",
    dataIndex: "id",
  },
  {
    title: "编程语言",
    dataIndex: "language",
  },
  {
    title: "判题结果",
    slotName: "result",
    align: "left",
  },
  {
    title: "消耗内存",
    slotName: "memory",
    align: "left",
  },
  {
    title: "执行用时",
    slotName: "time",
    align: "left",
  },
  // {
  //   title: "判题信息",
  //   slotName: "judgeInfo",
  // },
  {
    title: "判题状态",
    slotName: "status",
  },
  {
    title: "题目 id",
    dataIndex: "questionId",
  },
  {
    title: "提交者",
    dataIndex: "userVO.userName",
  },
  {
    title: "提交时间",
    slotName: "createTime",
  },
  {
    slotName: "optional",
    align: "left",
  },
];
const judgeResultObjtList = {
  Accepted: { text: `成功`, color: "#00b42a" },
  "Wrong Answer": { text: "答案错误", color: "#f53f3f" },
  "Runtime Error": { text: "运行错误", color: "#f53f3f" },
  "Dangerous Operation": { text: "危险操作", color: "#f53f3f" },
  "Compile Error": { text: "编译错误", color: "#ffb400" },
  "Time Limit Excessed": { text: "超时", color: "#0fc6c2" },
  "Memory Limit Excessed": { text: "内存溢出", color: "#ff7d00" },
  "Out Of Memory": { text: "内存不足", color: "#ff7d00" },
  "Output Limit Exceeded": { text: "输出溢出", color: "#ff7d00" },
  "Presentation Error": { text: "展示错误", color: "#0fc6c2" },
  Waiting: { text: "等待中", color: "#168cff" },
  "System Error": { text: "系统错误", color: "#86909c" },
  "Language UnSupported": { text: "语言不支持", color: "#0fc6c2" },
  "Sandbox System Error": { text: "沙箱系统错误", color: "#0fc6c2" },
  default: { text: "未知错误", color: "#86909c" },
};

const router = useRouter();
const store = useStore();

const getJudgeResultStyleColor = (judgeResult: string) => {
  if (
    judgeResult == undefined ||
    judgeResult == null ||
    judgeResult == "" ||
    judgeResultObjtList[judgeResult] == undefined ||
    judgeResultObjtList[judgeResult] == null
  ) {
    return judgeResultObjtList["default"].color;
  }
  return judgeResultObjtList[judgeResult].color;
};

/**
 * 跳转到题目提交的详情页（仅用户本人或管理员才可以查看）
 */
const toViewQuestionSubmitViewPage = (questionSumit: QuestionSubmitVO) => {
  // // 在新窗口中打开链接
  // window.open(`/view/question_submit/${questionSumit.id}`, "_blank");
  router.push({
    path: `/question_submit/detail/${questionSumit.id}`,
  });
};

/**
 * 根据条件搜索题目
 */
const doSubmit = () => {
  //重置页面为第一页
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
  // loadData();
};

/**
 * 分页大小
 * @param size
 */
const onPageSizeChange = (size: number) => {
  searchParams.value = {
    ...searchParams.value,
    pageSize: size,
  };
};
</script>

<style scoped>
#questionsSubmitView {
  max-width: 1400px;
  margin: 0 auto;
}
</style>
